package cn.kgc.ssm.controller;

import cn.hutool.core.util.IdUtil;
import cn.kgc.ssm.commons.ResponseResult;
import cn.kgc.ssm.entity.Course;
import cn.kgc.ssm.service.CourseService;
import org.apache.commons.io.IOUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

/**
 * @author 课工场
 * @date 2024/5/18
 * @description
 */

@RestController
@RequestMapping("course")
public class CourseController {

    @Resource
    private CourseService courseService;

    // 分页
    @RequestMapping("page")
    public ResponseResult coursePage(Integer page,Integer limit,String courseName){
        return courseService.coursePage(page,limit,courseName);
    }



    // 图片的获取  coursePicture
    @RequestMapping("coursePicture")
    public void coursePicture(String uuid, HttpServletResponse response) throws Exception {

        //TODO 项目开发完毕之后   部署服务器之前需要更改此处的路径
        FileInputStream fileInputStream = new FileInputStream("D:/upload/course/" + uuid);
        ServletOutputStream outputStream = response.getOutputStream();

        IOUtils.copy(fileInputStream,outputStream);
        fileInputStream.close();
        outputStream.close();

    }

    // 课程图片上传
    @RequestMapping("img/upload")
    public ResponseResult coursePictureUpload(MultipartFile file) throws Exception {

        if (file.isEmpty()){
            return  ResponseResult.fail().message("文件不能为空");
        }

        //TODO 项目开发完毕之后   部署服务器之前需要更改此处的路径
        File file1 = new File("D:/upload/course/");
        if (!file1.exists()){
            file1.mkdir();
        }


        // 处理文件的名字
        String originalFilename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        String uuid = IdUtil.simpleUUID();
        String lastName = uuid+"."+filenameExtension;

        File file2 = new File(file1, lastName);
        file.transferTo(file2);

        return  ResponseResult.success().data(lastName);
    }


    // 添加课程基本信息   uploadInfo
    @RequestMapping("uploadInfo")
    public ResponseResult  addUploadInfo(Course course)  {
        return  courseService.addUploadInfo(course);
    }


    // 根据课程id  获取课程信息
    @RequestMapping("getById")
    public ResponseResult  getCourseById(Integer id){
        return   courseService.getCourseById(id);
    }

    // 编辑课程信息
    @RequestMapping("edit")
    public ResponseResult  editCourse(Course course){
        return   courseService.editCourse(course);
    }


    // 删除课程信息
    @RequestMapping("delete")
    public ResponseResult  removeCourse(Integer id,String uuid){
        return   courseService.removeCourse(id,uuid);
    }



}
